<template>
  <div class="leaderboard-container">
    <div class="leaderboard-header">
      <h3>🏆 实时排行榜</h3>
      <el-button 
        size="small" 
        type="primary" 
        @click="refreshLeaderboard" 
        :loading="loading"
        :icon="Refresh"
      >
        刷新
      </el-button>
    </div>

    <div v-if="loading" class="loading">
      <el-skeleton :rows="5" animated />
    </div>

    <div v-else class="leaderboard-sections">
      <!-- 最佳榜 -->
      <div class="board-section">
        <h4>单局最佳榜</h4>
        <div v-if="bestLeaderboard.length === 0" class="empty-state">
          <el-empty description="暂无数据" />
        </div>
        <div v-else class="leaderboard-list">
          <div 
            v-for="player in bestLeaderboard" 
            :key="player.userId || player.nickname"
            :class="[
              'leaderboard-item',
              {
                'current-user': isCurrentUser(player.userId),
                'top-1': player.rank === 1,
                'top-2': player.rank === 2,
                'top-3': player.rank === 3
              }
            ]"
          >
            <div class="rank" :class="`rank-${player.rank}`">
              <span v-if="player.rank === 1">🥇</span>
              <span v-else-if="player.rank === 2">🥈</span>
              <span v-else-if="player.rank === 3">🥉</span>
              <span v-else>#{{ player.rank }}</span>
            </div>
            <div class="player-info">
              <div class="player-details">
                <div class="nickname">{{ player.nickname }}</div>
              </div>
            </div>
            <div class="total-area">
              <div class="area-value">{{ formatArea(player.bestArea) }}</div>
              <div class="area-label">最佳面积</div>
            </div>
          </div>
        </div>
      </div>

      <!-- 面积榜（累计） -->
      <div class="board-section">
        <h4>累计面积榜</h4>
        <div v-if="totalLeaderboard.length === 0" class="empty-state">
          <el-empty description="暂无数据" />
        </div>
        <div v-else class="leaderboard-list">
          <div 
            v-for="player in totalLeaderboard" 
            :key="player.userId || player.nickname"
            :class="[
              'leaderboard-item',
              {
                'current-user': isCurrentUser(player.userId),
                'top-1': player.rank === 1,
                'top-2': player.rank === 2,
                'top-3': player.rank === 3
              }
            ]"
          >
            <div class="rank" :class="`rank-${player.rank}`">
              <span v-if="player.rank === 1">🥇</span>
              <span v-else-if="player.rank === 2">🥈</span>
              <span v-else-if="player.rank === 3">🥉</span>
              <span v-else>#{{ player.rank }}</span>
            </div>
            <div class="player-info">
              <div class="player-details">
                <div class="nickname">{{ player.nickname }}</div>
              </div>
            </div>
            <div class="total-area">
              <div class="area-value">{{ formatArea(player.totalArea) }}</div>
              <div class="area-label">累计面积</div>
            </div>
          </div>
        </div>
      </div>
    </div>

    <!-- 当前用户排名提示 -->
    <div v-if="currentUserRankBest && currentUserRankBest > 5" class="current-user-rank">
      <el-alert 
        :title="`你的最佳榜排名: 第${currentUserRankBest}名`" 
        type="info" 
        :closable="false"
        show-icon
      />
    </div>
  </div>
</template>

<script setup>
import { ref, onMounted, onUnmounted } from 'vue'
import { Refresh } from '@element-plus/icons-vue'
import { useAuthStore } from '@/stores/auth'
import { fetchLeaderboard } from '@/services/leaderboardService'

const auth = useAuthStore()
const bestLeaderboard = ref([])
const totalLeaderboard = ref([])
const loading = ref(false)
const currentUserRankBest = ref(null)

// 判断是否为当前用户
const isCurrentUser = (userId) => {
  return auth.user && userId === auth.user.id
}

// 格式化面积显示
const formatArea = (area) => {
  if (area >= 1000000) {
    return `${(area / 1000000).toFixed(1)}M`
  } else if (area >= 1000) {
    return `${(area / 1000).toFixed(1)}K`
  }
  return Math.round(area)
}

// 获取排行榜数据
const getLeaderboard = async () => {
  loading.value = true
  try {
    const [best, total] = await Promise.all([
      fetchLeaderboard({ type: 'best', top: 5 }),
      fetchLeaderboard({ type: 'total', top: 5 })
    ])
    const bestSorted = [...best]
      .sort((a, b) => Number(b.bestArea || 0) - Number(a.bestArea || 0))
      .map((p, i) => ({ ...p, rank: i + 1 }))
    const totalSorted = [...total]
      .sort((a, b) => Number(b.totalArea || 0) - Number(a.totalArea || 0))
      .map((p, i) => ({ ...p, rank: i + 1 }))
    bestLeaderboard.value = bestSorted
    totalLeaderboard.value = totalSorted

    if (auth.user) {
      const userRankBest = bestSorted.find(player => player.userId === auth.user.id)
      currentUserRankBest.value = userRankBest ? userRankBest.rank : null
    }
  } catch (error) {
    console.error('Failed to get leaderboard:', error)
  } finally {
    loading.value = false
  }
}

// 刷新排行榜
const refreshLeaderboard = () => {
  getLeaderboard()
}

// 自动刷新（每30秒）
let refreshInterval = null

onMounted(() => {
  getLeaderboard()
  
  // 设置自动刷新
  refreshInterval = setInterval(() => {
    if (!loading.value) {
      getLeaderboard()
    }
  }, 30000)
})

// 组件卸载时清理定时器
onUnmounted(() => {
  if (refreshInterval) {
    clearInterval(refreshInterval)
  }
})
</script>

<style scoped>
.leaderboard-container {
  background: white;
  border-radius: 16px;
  padding: 24px;
  box-shadow: 0 8px 32px rgba(0, 0, 0, 0.1);
  margin-bottom: 24px;
}

.leaderboard-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 20px;
}

.leaderboard-header h3 {
  margin: 0;
  font-size: 1.5rem;
  color: #333;
  display: flex;
  align-items: center;
  gap: 8px;
}

.leaderboard-sections {
  display: grid;
  grid-template-columns: 1fr 1fr;
  gap: 16px;
}

.board-section {
  background: #ffffff;
  border-radius: 12px;
  padding: 16px;
  box-shadow: 0 4px 12px rgba(0,0,0,0.06);
}

.board-section h4 {
  margin: 0 0 12px 0;
  color: #333;
}

.loading {
  padding: 20px 0;
}

.empty-state {
  padding: 40px 0;
  text-align: center;
}

.leaderboard-list {
  display: flex;
  flex-direction: column;
  gap: 12px;
}

.leaderboard-item {
  display: flex;
  align-items: center;
  gap: 16px;
  padding: 16px;
  border-radius: 12px;
  background: #f8f9fa;
  transition: all 0.3s ease;
  border: 2px solid transparent;
}

.leaderboard-item:hover {
  transform: translateY(-2px);
  box-shadow: 0 4px 16px rgba(0, 0, 0, 0.1);
}

.leaderboard-item.current-user {
  border-color: #409eff;
  background: #ecf5ff;
}

/* Top ranks highlighting */
.leaderboard-item.top-1,
.leaderboard-item.top-2,
.leaderboard-item.top-3 {
  position: relative;
}

.leaderboard-item.top-1 {
  border-color: #ffd700;
  background: linear-gradient(180deg, rgba(255,215,0,0.08), #ffffff);
  box-shadow: 0 6px 20px rgba(255, 215, 0, 0.25);
}

.leaderboard-item.top-1::before {
  content: "";
  position: absolute;
  left: -2px;
  top: -2px;
  bottom: -2px;
  width: 6px;
  border-radius: 12px 0 0 12px;
  background: linear-gradient(180deg, #ffd700, #ffed4e);
}

.leaderboard-item.top-2 {
  border-color: #c0c0c0;
  background: linear-gradient(180deg, rgba(192,192,192,0.08), #ffffff);
  box-shadow: 0 6px 18px rgba(192, 192, 192, 0.25);
}

.leaderboard-item.top-2::before {
  content: "";
  position: absolute;
  left: -2px;
  top: -2px;
  bottom: -2px;
  width: 6px;
  border-radius: 12px 0 0 12px;
  background: linear-gradient(180deg, #c0c0c0, #e5e5e5);
}

.leaderboard-item.top-3 {
  border-color: #cd7f32;
  background: linear-gradient(180deg, rgba(205,127,50,0.08), #ffffff);
  box-shadow: 0 6px 18px rgba(205, 127, 50, 0.25);
}

.leaderboard-item.top-3::before {
  content: "";
  position: absolute;
  left: -2px;
  top: -2px;
  bottom: -2px;
  width: 6px;
  border-radius: 12px 0 0 12px;
  background: linear-gradient(180deg, #cd7f32, #daa520);
}

.rank {
  width: 48px;
  height: 48px;
  border-radius: 50%;
  display: flex;
  align-items: center;
  justify-content: center;
  font-weight: bold;
  font-size: 1.2rem;
  color: white;
  flex-shrink: 0;
}

.leaderboard-item.top-1 .rank {
  transform: scale(1.12);
}

.leaderboard-item.top-2 .rank,
.leaderboard-item.top-3 .rank {
  transform: scale(1.06);
}

.rank-1 {
  background: linear-gradient(135deg, #ffd700, #ffed4e);
  color: #b8860b;
}

.rank-2 {
  background: linear-gradient(135deg, #c0c0c0, #e5e5e5);
  color: #696969;
}

.rank-3 {
  background: linear-gradient(135deg, #cd7f32, #daa520);
  color: #8b4513;
}

.rank-4, .rank-5 {
  background: linear-gradient(135deg, #6c757d, #adb5bd);
  color: white;
}

.player-info {
  display: flex;
  align-items: center;
  gap: 12px;
  flex: 1;
}

.player-details {
  flex: 1;
}

.nickname {
  font-weight: 600;
  font-size: 1.1rem;
  color: #333;
  margin-bottom: 4px;
}

.leaderboard-item.top-1 .nickname {
  color: #b8860b;
  text-shadow: 0 1px 0 rgba(255, 255, 255, 0.5);
}

.leaderboard-item.top-2 .nickname {
  color: #555;
  text-shadow: 0 1px 0 rgba(255, 255, 255, 0.5);
}

.leaderboard-item.top-3 .nickname {
  color: #8b4513;
  text-shadow: 0 1px 0 rgba(255, 255, 255, 0.5);
}

.stats {
  display: flex;
  gap: 12px;
  font-size: 0.9rem;
  color: #666;
}

.best-area {
  background: #fff3cd;
  padding: 2px 8px;
  border-radius: 12px;
  color: #856404;
}

.total-area {
  text-align: right;
  flex-shrink: 0;
}

.area-value {
  font-size: 1.3rem;
  font-weight: bold;
  color: #28a745;
  margin-bottom: 4px;
}

.area-label {
  font-size: 0.8rem;
  color: #666;
  text-transform: uppercase;
  letter-spacing: 0.5px;
}

.current-user-rank {
  margin-top: 16px;
}

@media (max-width: 768px) {
  .leaderboard-container {
    padding: 16px;
  }
  
  .leaderboard-header h3 {
    font-size: 1.3rem;
  }
  
  .rank {
    width: 40px;
    height: 40px;
    font-size: 1rem;
  }
  
  .player-info {
    gap: 8px;
  }
  
  .stats {
    flex-direction: column;
    gap: 4px;
  }
  
  .total-area {
    text-align: center;
  }
}
</style>
